<template>
  <tl-sub-page :render="render" :visible.sync="visible" v-dialogDrag :title="'九宫格'" :close-on-click-modal="false" class="tl-dialog" append-to-body width="1000px" @open="open" @close="close">
    <!--表格渲染-->
    <el-table class="tl-table" ref="mainTable" height="300px" resizable-key="tableHeight" :resizable-refs="tableResizeRefs" v-loading="loading" :data="datas" @selection-change="doSelectChange" @sort-change="doSortChange" row-key="id" border fit :row-class-name="doChangeRowClassName">
      <el-table-column type="index" label="序号" width="55px" align="center"></el-table-column>
      <el-table-column prop="deptcommoncode" label="省区" width="150px" sort-by="deptcommoncode" align="center" header-align="center">
        <template slot-scope="scope">
          <el-select v-model="scope.row.deptcommoncode" filterable clearable :disabled="disabled">
            <el-option v-for="item in codeModel.deptCommonCodeList" :key="item.code" :label="item.name" :value="item.code" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="userrole" label="职务" min-width="150px" sort-by="userrole" align="center" header-align="center">
        <template slot-scope="scope">
          <el-input v-model="scope.row.userrole" :disabled="disabled"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="friendship" label="私交" width="160px" sort-by="friendship" align="center" header-align="center">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.friendship" controls-position="right" @change="changeTotalScore(scope.row)" :step="0.1" :min="0" :max="3" :precision="1" :disabled="disabled"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column prop="business" label="业务" width="160px" sort-by="business" align="center" header-align="center">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.business" controls-position="right" @change="changeTotalScore(scope.row)" :step="0.1" :min="0" :max="3" :precision="1" :disabled="disabled"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column prop="totalscore" label="综合得分" width="100px" sort-by="totalscore" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column label="操作" width="100px" v-slot="scope">
        <el-button type="danger" @click="deleteRow(scope.$index)" style="margin-left:10px">删除</el-button>
      </el-table-column>
    </el-table>
    <div class="button-container">
      <el-row>
        <el-col :span="24">
          <el-button type="text" size="medium" icon="el-icon-circle-plus-outline" @click="addSquaredData" :disabled="disabled">新增</el-button>
          <el-button class="save" style="float: right" type="primary" @click="doSaveSquared" :disabled="disabled" :loading="saveLoading">保存</el-button>
        </el-col>
      </el-row>
    </div>
    <div class="chart-container">
      <chart :dataList="dataList" :userRoles="userRoles" ref="chart" v-if="showChart" :showTitle1="false" :showTitle2="true"></chart>
    </div>
  </tl-sub-page>
</template>

<script>
/** mixins */
import { mixin_list } from '@tapui/mixins/mixin_list'
import { validateNull } from '@tapui/utils/validate'
/** 子组件 */
import tlEdit from './edit'
import chart from './chart.vue'
/** 工具类 */
import { getAction, putAction, postAction, deleteAction } from '@tapui/utils/http'
export default {
  name: 'mpmProjectSquared',
  mixins: [mixin_list],
  components: { tlEdit, chart },
  data() {
    return {
      description: '销售项目九宫格-列表查询',
      urlPrefix: '/mpm/projectSquared/',
      url: {
        queryLatestInfo: '/mpm/projectSquared/queryLatestInfo',
        doSaveSquared: '/mpm/projectSquared/doSaveSquared',
        queryCodeList: '/mpm/projectSquared/dataCodeList',
        queryChart: '/mpm/projectSquared/querySquaredInfo',
        queryFish: '/mpm/projectFishFirst/queryFishInfo'
      },
      // 排序参数
      sorterInfo: {
        sidx: 'sortcode',
        sord: 'asc'
      },
      pageInfo: {
        currentPage: 1, // 当前页面
        pageSize: 1000, // 每页记录数
        pageSizes: ['10', '50', '100'],
        totalCount: 0 // 总数
      },
      isQueryOnCreated: false,
      visible: false,
      dataList: [],
      userRoles: [],
      showChart: false,
      saveLoading: false,
      fishInfo: [],
      deptList: []
    }
  },
  props: {
    model: {
      default: function() {
        return {}
      },
      type: Object
    },
    render: {
      default: 'el-dialog',
      type: String
    },
    disabled: {
      type: Boolean,
      default: false
    },
    projectinfo: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  methods: {
    // 查询鱼骨图中职务数据，并初始化
    queryFishInfo() {
      getAction(this.url.queryFish, { taskid: this.model.id }).then((res) => {
        if (res.success) {
          this.fishInfo = res.result.fishbone
          this.deptList = this.fishInfo ? this.getDeptFromFish(this.fishInfo) : []
          this.addPostInfo(this.deptList)
        } else {
          this.$tap.alert('查询失败，请联系管理员!', 'warning')
        }
      })
    },
    // 从鱼骨图数据中，筛选出职务信息，前面附上部门信息
    getDeptFromFish(fishData) {
      let result = []
      for (let item of fishData) {
        item.children.length > 0
          ? item.children.map((sonItem) => {
              result.push(item.clientdept + sonItem.post)
            })
          : []
      }
      return result
    },
    // 新增时自动添加职务信息
    addPostInfo(postList) {
      if (!postList) {
        return
      }
      for (let item of postList) {
        this.datas.push({ taskid: this.model.id, projectcode: this.model.projectcode, deptcommoncode: this.projectinfo.deptcommoncode, userrole: item })
      }
    },
    deleteRow(index) {
      this.datas.splice(index, 1)
    },
    close() {
      this.showChart = false
    },
    open() {
      this.showChart = false
      this.queryLatestInfo()
    },
    queryLatestInfo() {
      this.datas = []
      if (!this.model.id) {
        return false
      }
      getAction(this.url.queryLatestInfo, { qry_taskid: this.model.id }).then((res) => {
        if (res.success) {
          this.datas = res.result
        } else {
          this.$tap.alert('查询失败，请联系管理员!', 'warning')
        }
      })
      getAction(this.url.queryChart, { taskid: this.model.id }).then((res) => {
        if (res.success) {
          if (res.result && res.result.datalist.length > 0) {
            this.dataList = res.result.datalist
            this.userRoles = res.result.userrole.split(',')
            this.showChart = true
            this.$nextTick(() => {
              this.$refs.chart.init()
            })
          } else {
            // 使用示例数据初始化并使用鱼骨图中的职务信息
            this.queryFishInfo()
            let exampleData = {
              datalist: [
                // {
                //   data: [[0.5, 0.3], [1.2, 1.3], [1.7, 2.0], [2.2, 2.4]],
                //   name: '职务1'
                // }
                {
                  data: [[0.4, 1.2], [1.4, 1.2], [2.4, 2.2]],
                  name: '职务1'
                }
              ],
              userrole: '职务1'
            }
            this.dataList = exampleData.datalist
            this.userRoles = exampleData.userrole.split(',')
            this.showChart = true
            this.$nextTick(() => {
              this.$refs.chart.init()
            })
          }
        } else {
          this.$tap.alert('九宫格数据查询失败，请联系管理员!', 'warning')
        }
      })
    },
    changeTotalScore(row) {
      row.totalscore = ((validateNull(row.friendship) ? 0 : row.friendship) * 10 * ((validateNull(row.business) ? 0 : row.business) * 10)) / 100
    },
    addSquaredData() {
      this.datas.push({ taskid: this.model.id, projectcode: this.model.projectcode, deptcommoncode: this.projectinfo.deptcommoncode })
    },
    minusSquaredData() {
      if (this.datas.length > 0) {
        this.datas.pop()
      }
    },
    doSaveSquared() {
      this.$tap.confirm('确定保存客户关系吗？').then(() => {
        this.handleSave()
      })
    },
    handleSave() {
      if (this.datas.length === 0) {
        this.$tap.alert('请填写客户关系内容！')
        return false
      }
      for (let item of this.datas) {
        if ((!item.deptcommoncode && item.deptcommoncode !== 0) || !item.userrole || (!item.friendship && item.friendship !== 0) || (!item.business && item.business !== 0)) {
          this.$tap.alert('请完善客户关系的所有内容！')
          return false
        }
      }
      this.saveLoading = true
      postAction(this.url.doSaveSquared, { data: this.datas, qry_state: this.model.state }).then((res) => {
        if (res.success) {
          this.saveLoading = false
          this.$tap.message('保存成功!', 'success')
          this.queryLatestInfo()
        } else {
          this.saveLoading = false
          this.$tap.alert('保存失败，请联系管理员！', 'warning')
        }
      })
    }
  },
  updated() {
    if (this.$refs.mainTable) {
      this.$refs.mainTable.doLayout()
    }
  }
}
</script>

<style scoped>
.button-container {
  margin-top: 8px;
}
.chart-container {
  padding-left: 250px;
  margin-top: 50px;
  margin-bottom: 50px;
}
.save {
  margin-top: 5px;
}
</style>
